﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common;
using System.Data;
using System.Data.SqlClient;
using Maticsoft.DBUtility;
using System.Text;

namespace School.Admin
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session.Remove("WebSessions");
                Session.Remove("UserName");
                Session.RemoveAll(); //用于结果了所有的键值
                Session.Abandon(); //用于结果了当前会话
            }
        }

        public bool Exists(string UserName, string Password)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from Users");
            strSql.Append(" where MembeLoginName=@MembeLoginName and MembePassWord = @MembePassWord");
            SqlParameter[] parameters = {
					new SqlParameter("@MembeLoginName", UserName),
                    new SqlParameter("@MembePassWord", Password)};

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }

        protected void LoginButton_Click(object sender, EventArgs e)
        {
            //if (Session["CheckCodes"] == null)
            //{
            //    ScriptHelper.AlertRedirect("验证码过期，请重新登录！", "login.aspx");
            //    return;
            //}
            //if (this.CheckCode.Text.Trim().ToUpper() != Session["CheckCodes"].ToString())
            //{
            //    ScriptHelper.Alert("验证码不正确！");
            //    return;
            //}
            //else
            {
                string PassWord = Encryption.GetMD5(txt_PassWord.Value.Trim());

                if (Exists(txt_UserName.Value, PassWord))
                {
                    DataSet ds = new BLL.Users().GetList("MembeLoginName='" + txt_UserName.Value + "' and MembePassWord='" + PassWord + "'");
                    //写入Session,id,登录名,最后一次登录时间,登录IP
                    WebSessions m_WebSession = new WebSessions(
                        ds.Tables[0].Rows[0]["ID"].ToString(),
                        ds.Tables[0].Rows[0]["MembeLoginName"].ToString());
                    Session["WebSessions"] = m_WebSession;
                    Session["MemberName"] = m_WebSession.UserName;//用户名


                    Response.Redirect("main.html");
                }
                else
                {
                    Utility.JavaScript.JsScript(this, "alert('管理员或密码错误，请重新输入。');window.location.href='login.aspx';");
                }
            }
        }
    }
}